# coding: utf-8
from datetime import datetime
from django.db import models
from lib.common import BasicManager
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from project.settings import DEFAULT_PAGESIZE
from lib.sms.sender import variable_send, send_notice
from services.datamodel.student.models import mm_Student, mm_StudentChannel
import json


class ModelManagerSmsTemplate(BasicManager):

    def get_template_list(self, page=None):
        result = self.values().order_by("-created_at")
        if not page:
            return {'retlist': list(result)}
        paginator = Paginator(result, DEFAULT_PAGESIZE)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False, 'retcode': 0}
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages, 'retcode': 0}

    def sending(self, t_id, intention=None, difference_id=None, headmaster_id=None, snad_id=None, launch_id=None,
                launch_dynamic_id=None, is_wechat=None, group=None):
        try:
            res = self.filter(id=t_id).first()
            if group:
                result = mm_StudentChannel.values("student__mobile", "id", "student_id").order_by("-created_at")
                if intention:
                    result = result.filter(student__intention__in=json.loads(intention))
                if headmaster_id:
                    result = result.filter(student__headmaster_id=headmaster_id)
                if launch_id:
                    result = result.filter(launch_id=launch_id)
                if launch_dynamic_id:
                    result = result.filter(launch_dynamic_id=launch_dynamic_id)
                if is_wechat:
                    result = result.filter(is_wechat=is_wechat)
                working = True
                i = 1
                difference = json.loads(difference_id)
                while working == True:
                    paginator = Paginator(result, 50)
                    try:
                        result_page = paginator.page(i)
                        for v in result_page:
                            if v['student_id'] in difference:
                                continue
                            if res.types == 1:
                                variable_send(v['student__mobile'], res)
                            else:
                                send_notice(v['student__mobile'], res.content)
                        i += 1
                    except EmptyPage:
                        working = False
            else:
                # 单独发送
                result = mm_Student.filter(id__in=json.loads(snad_id)).values("mobile")
                for v in result:
                    if res.types == 1:
                        variable_send(v['mobile'], res)
                    else:
                        send_notice(v['mobile'], res.content)
            return True
        except:
            return False


class SmsTemplate(models.Model):
    content = models.TextField("短信内容", default='')
    name = models.CharField("短信备注名称", max_length=20, default='')
    var = models.CharField("短信动态变量", max_length=100, default='')
    types = models.PositiveSmallIntegerField("短信类型", default=0)  # 0: 默认常规短信   1:变量短信
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerSmsTemplate()

    class Meta:
        verbose_name = '短信模板'
        verbose_name_plural = verbose_name
        db_table = "momself_sms_template"


mm_SmsTemplate = SmsTemplate.objects
